﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hxj.Data;
using System.Data;
using Utility;
using Utility.Json;
using MsgCenter.DAL.Base;
using Utility.Model;
using Utility.Comm;
using MsgCenter.BLL;

namespace MsgCenter.BLL.Impl
{
    /// <summary>
    /// 用户管理业务层
    /// </summary>
    public class BLL_SysUser
    {
        private readonly BaseService dal = new BaseService();
        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        public JsonJqGridData GetUserList(PagerCondition pager)
        {
            try
            {
                pager.RecordCount = dal.GetDataBase().From<Sys_User>()
                                                          .LeftJoin<Sys_Dept>(Sys_Dept._.ID == Sys_User._.DeptGuID)
                                                          .Where(pager.ComplexSearchCondition)
                                                          .Count();

                #region 固定写法，判断当前页面对象删除后，当前页和最大页之间的关系
                if (pager.CurrentPage > pager.PageCount)
                    pager.CurrentPage = pager.PageCount;
                #endregion

                if (pager.OrderBy == null)
                    pager.OrderBy = new OrderByClip(Sys_User._.CreateDate, OrderByOperater.DESC);

                using (DataTable dt = dal.GetDataBase().From<Sys_User>() //选择表
                                             .LeftJoin<Sys_Dept>(Sys_Dept._.ID == Sys_User._.DeptGuID)
                                             .Select(Sys_User._.All, Sys_Dept._.DeptName)  //设置选择的字段数目
                                             .Page(pager.PageSize, pager.CurrentPage)  //分页显示
                                             .Where(pager.ComplexSearchCondition)   //条件
                                             .OrderBy(pager.OrderBy)   //排序
                                             .ToDataTable())   //返回datatable
                {
                    SetUserRoles(dt);
                    JsonJqGridData grid = new JsonJqGridData();
                    grid.page = pager.CurrentPage;
                    grid.rows = dt;
                    grid.records = pager.RecordCount;
                    grid.total = pager.PageCount;
                    return grid;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void SetUserRoles(DataTable dt)
        {
            DataColumn dtColumn = new DataColumn();
            dtColumn.ColumnName = "UserRole";
            dt.Columns.Add(dtColumn);
            dtColumn = new DataColumn();
            dtColumn.ColumnName = "UserRoleID";
            dt.Columns.Add(dtColumn);
            Dictionary<string, string> dicUserRole = null;
            string strUserRole = string.Empty;
            string strUserRoleID = string.Empty;
            foreach (DataRow drUser in dt.Rows)
            {
                strUserRole = string.Empty;
                strUserRoleID = string.Empty;
                dicUserRole = GetLoginUserRoles(drUser["UserID"].ToSafeString());
                if (dicUserRole.Count > 0)
                {
                    foreach (KeyValuePair<string, string> item in dicUserRole)
                    {
                        if (strUserRole.Length == 0)
                        {
                            strUserRole = item.Value;
                            strUserRoleID = item.Key;
                        }
                        else
                        {
                            strUserRole += "," + item.Value;
                            strUserRoleID += "," + item.Key;
                        }
                    }
                }
                drUser["UserRole"] = strUserRole;
                drUser["UserRoleID"] = strUserRoleID;
            }
        }

        /// <summary>
        /// 根据条件获取用户Table
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public DataTable GetUserTable(WhereClip wcp, OrderByClip OrderBy)
        {
            if (OrderBy != null)
            {
                return dal.GetDataBase().From<Sys_User>() //选择表
                                                 .LeftJoin<Sys_Dept>(Sys_Dept._.ID == Sys_User._.DeptGuID)
                                                 .Select(Sys_User._.All, Sys_Dept._.DeptName)  //设置选择的字段数目
                                                 .Where(wcp)
                                                 .OrderBy(OrderBy)
                                                 .ToDataTable();
            }
            else
            {
                return dal.GetDataBase().From<Sys_User>() //选择表
                                                 .LeftJoin<Sys_Dept>(Sys_Dept._.ID == Sys_User._.DeptGuID)
                                                 .Select(Sys_User._.All, Sys_Dept._.DeptName)  //设置选择的字段数目
                                                 .Where(wcp)
                                                 .ToDataTable();
            }
        }
        /// <summary>
        /// 根据条件获取用户List
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public List<Sys_User> GetUserList(WhereClip wcp)
        {
            return dal.GetDataBase().From<Sys_User>().Where(wcp).ToList();
        }
        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="model">用户实体</param>
        /// <param name="list">用户对应的角色列表</param>
        public void Save(Sys_User model, List<Sys_UserRoles> list)
        {
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                dal.Save<Sys_User>(model, trans);
                dal.ExecuteNonQuery("delete Sys_UserRoles where UserID='" + model.UserID + "'");
                if (list != null)
                {
                    foreach (Sys_UserRoles modelRoles in list)
                    {
                        dal.Save<Sys_UserRoles>(modelRoles, trans);
                    }
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
            }
        }
        /// <summary>
        /// 删除用户,修改状态为已删除
        /// </summary>
        /// <param name="strDataID"></param>
        public void Delete(string strDataID)
        {
            if (strDataID.Length > 0)
            {
                string[] idList = strDataID.Trim(',').Split(',');
                DbTrans trans = dal.GetDataBase().BeginTransaction();
                try
                {
                    foreach (string strUserID in idList)
                    {
                        dal.ExecuteNonQuery("Update Sys_User set Isdelete=1 where UserID='" + strUserID + "'", trans);
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    trans.Close();
                }
            }
        }
        /// <summary>
        /// 获取用户对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_User GetModel(WhereClip wcp)
        {
            return dal.GetModel<Sys_User>(wcp);
        }
        /// <summary>
        /// 获取用户对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_User GetModel(string id)
        {
            return dal.GetModel<Sys_User>(Sys_User._.UserID == id);
        }
        /// <summary>
        /// 获取用户对应的角色
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public DataTable GetUserRoles(string strUserID)
        {
            return dal.GetTable<Sys_UserRoles>(Sys_UserRoles._.UserID == strUserID);
        }
        /// <summary>
        /// 获取权限创建树
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public DataSet GetAllList(string UserID)
        {
            string strSql = "select *  FROM Sys_Module where isdelete=0 order by fatherid,sort";
            strSql += " SELECT  b.UserID, a.ModuleID, a.ModuleName,a.FatherID, a.LinkAddress, a.sort, a.ID,a.IsDelete, a.CssCss FROM Sys_Module AS a INNER JOIN Sys_UserOperate AS b ON a.ID = b.ModuleID AND b.OperateID='00000000-0000-0000-0000-000000000000' WHERE (a.IsDelete = 0) and b.UserID='" + UserID.ToSafeString() + "'";
            strSql += " SELECT a.ModuleID, a.OperateID, b.OperateName, b.OperateValue, b.IsDelete, b.Createdate FROM Sys_ModuleOperate AS a INNER JOIN Sys_Operate AS b ON a.OperateID = b.OperateID WHERE     (b.IsDelete = 0)";
            strSql += "SELECT     a.UserID, a.ModuleID, a.OperateID, b.OperateName, b.Createdate, b.IsDelete, b.OperateValue FROM Sys_UserOperate AS a INNER JOIN Sys_Operate AS b ON a.OperateID = b.OperateID AND a.OperateID<>'00000000-0000-0000-0000-000000000000' WHERE (b.IsDelete = 0) and a.UserID='" + UserID.ToSafeString() + "'";
            return dal.GetDataBase().FromSql(strSql).ToDataSet();
        }
        /// <summary>
        /// 保存用户权限
        /// </summary>
        /// <param name="strUserID"></param>
        /// <param name="strSelectAuth"></param>
        public void SaveUserAuth(string strUserID, string strSelectAuth)
        {
            BLLServiceHelper.GetOperateService().SaveStartNull();
            string UserID = strUserID.ToSafeString();
            if (strSelectAuth.IsNullOrEmpty())
            {
                dal.ExecuteNonQuery("delete Sys_UserOperate where UserID='" + UserID + "'");
                return;
            }
            if (strSelectAuth.Length > 0)
            {
                DbTrans trans = dal.GetDataBase().BeginTransaction();
                try
                {
                    dal.ExecuteNonQuery("delete Sys_UserOperate where UserID='" + UserID + "'", trans);
                    string[] strDataAuth = strSelectAuth.Split(',');
                    int DataAuth_Len = strDataAuth.Length;
                    if (DataAuth_Len > 0)
                    {
                        string[] sz1;
                        string ModuleID;
                        string OperateID;
                        foreach (string strAuth in strDataAuth)
                        {
                            sz1 = strAuth.Split('$');
                            if (sz1.Length > 1)
                            {
                                ModuleID = sz1[0].ToSafeString();
                                OperateID = sz1[1].ToSafeString();
                            }
                            else
                            {
                                ModuleID = sz1[0].ToSafeString();
                                OperateID = Guid.Empty.ToSafeString();
                            }
                            if (ModuleID != Guid.Empty.ToSafeString())
                            {
                                dal.ExecuteNonQuery("insert into Sys_UserOperate(UserID,ModuleID,OperateID)  values ('" + UserID + "','" + ModuleID + "','" + OperateID + "')", trans);
                            }
                        }
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    trans.Close();
                }
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="strUserName"></param>
        /// <returns></returns>
        public Sys_User GetLogin(string strUserName)
        {
            return dal.GetModel<Sys_User>(Sys_User._.UserName == strUserName && Sys_User._.IsDelete == false);
        }
        /// <summary>
        /// 获取用户模块权限
        /// </summary>
        /// <param name="strUserID"></param>
        /// <returns></returns>
        public List<Sys_Module> GetLoginUserModule(string strUserID, bool isAdmin)
        {
            string strSql = string.Empty;
            if (isAdmin)
            {
                strSql = "select a.ID,a.ModuleName,a.ModuleDes,a.ModuleID,a.FatherID,a.Sort,a.LinkAddress,a.CssCss,a.CreateDate,a.CreateUser,a.IsDelete from Sys_Module as a where a.IsDelete=0 order by ModuleID,Sort";
            }
            else
            {
                strSql = @"select Distinct * from (
 (select a.ID,a.ModuleName,a.ModuleDes,a.ModuleID,a.FatherID,a.Sort,a.LinkAddress,a.CssCss,a.CreateDate,a.CreateUser,a.IsDelete from 
 Sys_Module as a,Sys_RoleOperate as b,Sys_UserRoles as c where a.IsDelete=0 and a.ID=b.ModuleID and b.RoleID=c.RoleID and c.UserID='{0}' and b.OperateID='00000000-0000-0000-0000-000000000000')
union all
 (select a.ID,a.ModuleName,a.ModuleDes,a.ModuleID,a.FatherID,a.Sort,a.LinkAddress,a.CssCss,a.CreateDate,a.CreateUser,a.IsDelete from 
 Sys_Module as a,Sys_UserOperate as b where a.IsDelete=0 and a.ID=b.ModuleID and b.UserID='{0}' and b.OperateID='00000000-0000-0000-0000-000000000000')
) as t order by ModuleID,Sort";
                strSql = string.Format(strSql, strUserID);
            }
            List<Sys_Module> dicList = new List<Sys_Module>();
            using (IDataReader dr = dal.GetDataReader(strSql))
            {
                Sys_Module model = null;
                while (dr.Read())
                {
                    model = new Sys_Module();
                    model.SetPropertyValues(dr);
                    dicList.Add(model);
                }
                dr.Close();
                dr.Dispose();
            }
            return dicList;
        }
        /// <summary>
        /// 获取用户模块功能权限
        /// </summary>
        /// <param name="strUserID"></param>
        /// <returns></returns>
        public Dictionary<string, List<Sys_Operate>> GetLoginUserOperate(string strUserID, bool isAdmin)
        {
            string strSql = string.Empty;
            if (isAdmin)
            {
                strSql = "select b.ModuleID, c.* from Sys_ModuleOperate as b,Sys_Operate as c where c.IsDelete=0 and b.OperateID=c.OperateID order by ModuleID, CreateDate";
            }
            else
            {
                strSql = @"select Distinct * from (
 (select b.ModuleID, a.OperateID,a.OperateName,a.OperateValue,a.OperateDes,a.IsDelete,a.CssCss,a.CreateDate,a.CreateUser,a.CssCssGrid,a.FunOption from 
 Sys_Operate as a,Sys_RoleOperate as b,Sys_UserRoles as c where a.IsDelete=0 and a.OperateID=b.OperateID and b.RoleID=c.RoleID and c.UserID='{0}'and b.OperateID<>'00000000-0000-0000-0000-000000000000')
union all
 (select  b.ModuleID,a.OperateID,a.OperateName,a.OperateValue,a.OperateDes,a.IsDelete,a.CssCss,a.CreateDate,a.CreateUser,a.CssCssGrid,a.FunOption from 
 Sys_Operate as a,Sys_UserOperate as b where a.IsDelete=0 and a.OperateID=b.OperateID and b.UserID='{0}' and b.OperateID<>'00000000-0000-0000-0000-000000000000')
) as t order by ModuleID,CreateDate";
                strSql = string.Format(strSql, strUserID);
            }
            Dictionary<string, List<Sys_Operate>> dicList = new Dictionary<string, List<Sys_Operate>>();
            using (DataTable dtUserOperate = dal.GetTable(strSql))
            {
                List<Sys_Operate> listOperate;
                Sys_Operate model;
                var query = from t in dtUserOperate.AsEnumerable()
                            group t by new { t1 = t.Field<string>("ModuleID") } into m
                            select new
                            {
                                name = m.Key.t1
                            };
                if (query.ToList().Count > 0)
                {
                    query.ToList().ForEach(q =>
                    {
                        listOperate = new List<Sys_Operate>();
                        IEnumerable<DataRow> dr = dtUserOperate.AsEnumerable().Where<DataRow>(r => (r.Field<string>("ModuleID") == q.name));
                        foreach (DataRow drOperate in dr)
                        {
                            model = new Sys_Operate();
                            model.SetPropertyValues(drOperate);
                            listOperate.Add(model);
                        }
                        dicList.Add(q.name.ToString(), listOperate);
                    });
                }
                return dicList;
            }
        }
        /// <summary>
        /// 通过用户ID获取用户所属角色
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetLoginUserRoles(string UserID)
        {
            Dictionary<string, string> dicList = new Dictionary<string, string>();
            string strSql = "select a.RoleID,a.RoleName from Sys_Role as a,Sys_UserRoles as b where a.RoleID=b.RoleID and b.UserID='" + UserID + "'";
            using (IDataReader dr = dal.GetDataReader(strSql))
            {
                while (dr.Read())
                {
                    dicList.Add(dr["RoleID"].ToString(), dr["RoleName"].ToString());
                }
                dr.Close();
                dr.Dispose();
            }
            return dicList;
        }
    }
}
